
const { exec } = require('child_process');
const util = require('util');
const execPromise = util.promisify(exec);
const { loading, stopLoading, loadingSucceed, loadingFailed, print, printWarning } = require('./message-box');

const runCommands = (commands, config) => Promise.all(commands.map((com) => new Promise(async (resolve) => {
    let result;
    const { showLoadingTips = true, loadingTips, showSuccessTips = true, successTips } = config || {};
    let comNames = com.split('&&').map(c => c.trim());
    if (comNames.length > 1 && comNames[0].includes('cd')) comNames.splice(0, 1);
    if (showLoadingTips) loading(loadingTips || `exec command '${comNames}' is running...`);
    try {
        result = await execPromise(com, { stdio: 'inherit' });
        if (showSuccessTips) loadingSucceed(successTips || `'${comNames}' running succeed!`);
    } catch (error) {
        loadingFailed(`exec command fail at: '${comNames}'`);
        print(`ERROR:${JSON.stringify(error)}\n`);
        result = { status: 'error', error: JSON.stringify(error) };
    }
    stopLoading();
    setTimeout(() => {
        resolve(result);
    }, 200);
})));

module.exports = async function execCommands(commands, config) {
    let results = [];
    return new Promise(async (resolve) => {
        if (!commands || !commands.length) return resolve(results);
        if (Object.prototype.toString.call(commands) === '[object String]') commands = [commands];
        if (Object.prototype.toString.call(commands) === '[object Array]') results = await runCommands(commands, config);
        resolve(results)
    });
}
